package cn.tedu.ivos.base.exception;


import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleServiceException(ServiceException ex){
        log.error("业务层异常:" + ex.getStatusCode().getMessage());
        return new JsonResult(ex.getStatusCode());
    }
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String data = ex.getMessage();
        log.error("IllegalArgumentException:" + data);
        return JsonResult.fail(data);
    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:" + data);
        return new JsonResult(StatusCode.VALIDATE_ERROR, data);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + data);
        return new JsonResult(StatusCode.VALIDATE_ERROR, data);
    }
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("RuntimeException:" + data);
        return JsonResult.fail(data);
    }
}